Conditional rendering in React
Let’s create a simple class-based component that has only one state – pet. This component will render a button, which when clicked, changes the state of the pet. If the pet is a cat, it will be changed into the dog, and if it is set to a dog, the state will go back to the ‘cat’.
Make sense? Okay, let’s start with the code. We have a basic structure here as:
class App extends React.Component { constructor() { super() this.state = { pet: 'cat' } } handleClick(e) {} render() { return () } } ReactDOM.render( < App / > , document.getElementById('root'))
To call our function handleClick()
that toggles the state of the component, let’s create a <button>
in the render method.
render() { return ( <button onClick = { this.handleClick } > Click here </button> ) }
To work with handleClick()
event, we need to bind this function in the constructor()
method of the component.
constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) this.state = { pet: 'cat' } }
Now, let’s write down the logic of handleClick()
function.
handleClick(e) { e.preventDefault(); console.log(this.state.pet) if (this.state.pet === 'cat') { this.setState({ pet: 'dog' }) } else { this.setState({ pet: 'cat' }) } }
As we have learned in the previous lessons, we can’t return false in the functions and have to use e.preventDefault() method to stop the default behavior of the button.
In the next statement, we are simply printing the value of the state.pet to the console.
The following is a simple if-else statement.
if (this.state.pet === 'cat') { // set state.pet to dog } else { //set state.pet to cat }
Putting everything together, we will have the following piece of code.
index.js
import React from 'react' import ReactDOM from 'react-dom' class App extends React.Component { constructor(props) { super(props) this.handleClick = this.handleClick.bind(this) this.state = { pet: 'cat' } } handleClick(e) { e.preventDefault(); console.log(this.state.pet) if (this.state.pet === 'cat') { this.setState({ pet: 'dog' }) } else { this.setState({ pet: 'cat' }) } } render() { return ( <button onClick = { this.handleClick } > Click here < /button> ) } } ReactDOM.render( < App / > , document.getElementById('root'))
Inline if-else with the ternary conditional operator
You can also use JavaScript’s short version of the if-else operator, known as ternary conditional operator to control the flow of your app.
The syntax of the ternary operator is: condition? True-state: false-statement
handleClick(e) { e.preventDefault(); console.log(this.state.pet) this.state.pet === 'cat' ? this.setState({ pet: 'dog' }) : this.setState({ pet: 'cat' }) }
I tried to keep the example, as simple as possible. But if you still have any question related to this lesson, feel free to leave it in the comments section below.
React Event Handling << | Tutorial Home | >>React Forms Handle |
Comments